package com.grts.mall.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.grts.mall.AlipayConfig;
import com.grts.mall.common.CommonResult;
import com.grts.mall.pojo.Cart;
import com.grts.mall.pojo.Order;
import com.grts.mall.service.OrderService;

@RestController
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ObjectMapper objectMapper;
	
	@RequestMapping("/order")
	public CommonResult add(@RequestBody List<Cart> vos) throws JsonProcessingException{
		 return this.orderService.add(vos);
	}
	
	@RequestMapping("/order/hander")
	public String hander(Long oid) throws Exception {
//		String outTradeNo = oid.toString();
//		String subject = "订单名"+oid;
//		Order order = this.orderService.findById(oid);
//		String totalAmount = order.getTotalAmount().toString();
//		
//		
//		AlipayTradePagePayResponse pay = Factory.Payment.Page().pay(subject, outTradeNo, totalAmount, "http://localhost:8082/finalyhandler");
//		String body = pay.body;
//		return body;
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
		
		String out_trade_no = oid.toString();
		String total_amount = this.orderService.findById(oid).getTotalAmount().toString();
		String subject = "订单名"+oid;
		
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
				+ "\"total_amount\":\""+ total_amount +"\"," 
				+ "\"subject\":\""+ subject +"\"," 
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		
		String result = alipayClient.pageExecute(alipayRequest).getBody();
		return result;
	}
	
	@RequestMapping("/finalyhandler")
	public String view(HttpServletRequest map) throws UnsupportedEncodingException, AlipayApiException {
		Map<String,String> params = new HashMap<String,String>();
		Map<String, String[]> requestParams = map.getParameterMap();
		
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
			System.out.println(params.get(name));
		}
		boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
		if (signVerified) {
			return "sucess";
		}else {
			return "badres";
		}
	}
	
}
